<?php


namespace app\admin\controller;


use app\service\orderService;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\db\Where;
use think\facade\Db;
use think\facade\View;

class Bill extends Common
{
    public function billList(){
        $adminId = session('id');
        $usertype = Db::name('admin')->where('id',$adminId)->value('usertype');
        View::assign('usertype',$usertype);
        //根据当前账号查询区域
        $com = $this->pidTokenId();
        $whe=new Where();
        //$com['community_id']=implode(',',$com['community_id']);
        $whe['id'] = array('in',$com['parking_id']);

        //根据账号查询停车场
        $parkinglist = (new orderService())->parkingList($whe);

        View::assign('parkinglist',$parkinglist);
        //$parkingNo = $this->getParkingNo();
        //搜索
        $data = request()->get();
        //var_dump($data);
        //$where=new Where();
        $where=array();
        $clientList=array();
        if (!empty($data)){

            if(!empty($data['plateNumber'])){
                $where[]=['plateNumber','like','%'.$data['plateNumber'].'%'];
            }
            if(!empty($data['parkingNume'])){
                $where[]=['parkingNume','like','%'.$data['parkingNume'].'%'];
            }

        }
        View::assign("clientList",$clientList);
        //var_dump($where);
        //$where=array_filter($where);
        $export = $where;
        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        View::assign('export',$export);
        $page = request()->has('page') ? request()->get('page') : 1;
        //多条件查询地库车位信息

        $query=array_filter($where);
        $orderlist =Db::name('cxyun_pay_bill')
            ->where($where)
            ->order("id desc")
            ->paginate(100, false, [
                'page'  =>  $page,
                'query' =>  $query
            ]);
        $list=[];
        foreach ($orderlist as $info){
            $roominfo=Db::table("roominfo")->where("id",$info["room_id"])->find();
            if(empty($roominfo)){
                $info["address"]='';
            }else{
                $info["address"]=$roominfo["group"].$roominfo["building"]."-".$roominfo["unit"]."-".$roominfo["room"];

            }
            $info["duration"]=convertTime($info["stopTime"]*60);
            $list[]=$info;
        }

        $number = Db::name('cxyun_pay_bill')
            ->where($where)
            ->count();
        View::assign('number',$number);
        View::assign('list',$list);
        View::assign('orderlist',$orderlist);
        foreach ($data as $k => $v) {
            View::assign($k, $v);

        }
        return  View::fetch('bill_list');
    }

    public function orderExcel(){

        //获取账单数据
        $export = request()->param('export');
        $export = str_replace("|","\"",$export);

        $where = json_decode($export,true);

        $orderlist =Db::name('cxyun_pay_bill')
            ->where($where)
            ->order("id desc")
            ->select();
        if(empty($orderlist)){
            return "没有数据";
        }

        $newExcel = new Spreadsheet();  //创建一个新的excel文档
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
        //设置宽度为true,不然太窄了
        $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);

        //设置第一栏的标题

        $objSheet->setTitle('停车账单');  //设置当前sheet的标题
        //设置第一栏的标题
        $objSheet->setCellValue('A1', '停车场')
            ->setCellValue('B1', '车牌')
            ->setCellValue('C1', '应付金额')
            ->setCellValue('D1', '实收金额')
            ->setCellValue('E1', '付款方式')
            ->setCellValue('F1', '缴费时间')
            ->setCellValue('G1', '入场时间')
            ->setCellValue('H1', '出场时间')
            ->setCellValue('I1', '停车时长')
            ->setCellValue('J1', '外部订单号')
            ->setCellValue('K1', '订单号');


        $i=2;  //定义一个i变量，目的是在循环输出数据是控制行数
        $count =Db::name('cxyun_pay_bill')->where($where)->count();  //计算有多少条数据
        for ($i = 2; $i <= $count+1; $i++) {
            $objSheet->setCellValue('A' . $i, $orderlist[$i-2]["parkingNume"]);
            $objSheet->setCellValue('B' . $i, $orderlist[$i-2]["plateNumber"]);
            $objSheet->setCellValue('C' . $i, $orderlist[$i-2]["amount"]);
            $objSheet->setCellValue('D' . $i, $orderlist[$i-2]["amount"]);
            $paytype="支付宝扫码";
            if($orderlist[$i-2]["scenes"]=="2"){
                $paytype="支付宝预支付";
            }
            if($orderlist[$i-2]["scenes"]=="3"){
                $paytype="微信扫码";
            }
            if($orderlist[$i-2]["payType"]=="4"){
                $paytype="微信预支付";
            }
            $objSheet->setCellValue('E' . $i,$paytype);
            $objSheet->setCellValue('F' . $i, $orderlist[$i-2]["createTime"]);
            $objSheet->setCellValue('G' . $i, $orderlist[$i-2]["inTime"]);
            $objSheet->setCellValue('H' . $i, $orderlist[$i-2]["outTime"]);
            $objSheet->setCellValue('I' . $i, convertTime($orderlist[$i-2]["stopTime"]));
            $objSheet->setCellValue('J' . $i, $orderlist[$i-2]["out_trade_no"]);
            $objSheet->setCellValue('K' . $i, $orderlist[$i-2]["trade_no"]);

        }
        $this->downloadExcel($newExcel, "停车账单", 'Xls');
    }
    function downloadExcel($newExcel, $filename, $format)
    {
        // $format只能为 Xlsx 或 Xls
        if ($format == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($format == 'Xls') {
            header('Content-Type: application/vnd.ms-excel');
        }

        header("Content-Disposition: attachment;filename="
            . $filename . date('Y-m-d') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, $format);

        $objWriter->save('php://output');

        //通过php保存在本地的时候需要用到
        //$objWriter->save($dir.'/demo.xlsx');

        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
//         If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        exit;
    }
}